package com.bingqing.controller;

import cn.hutool.json.JSON;
import com.bingqing.common.AutoLog;
import com.bingqing.common.CaptureConfig;
import com.bingqing.common.Result;
import com.bingqing.entity.Admin;
import com.bingqing.entity.Params;
import com.bingqing.service.AdminService;
import com.github.pagehelper.PageInfo;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * ClassName: AdminController
 * Package: com.bingqing.springboot.controller
 * Description:
 *
 * @Author liuyujie
 * @Create 2024-03-06 13:43
 * @Version 1.0
 */
@RestController
@RequestMapping("/admin")
@CrossOrigin //解决跨域问题
public class AdminController {
    @Resource
    private AdminService adminService;


    @GetMapping("/search")
    public Result findBySearch(Params params) {
        PageInfo<Admin> info = adminService.findBySearch(params);
        return Result.success(info);
    }
    //@PostMapping("/save")
    //public Result save(@RequestBody Admin admin){
    //    if(admin.getId() == null){
    //        adminService.add(admin);
    //    }else {
    //        adminService.update(admin);
    //    }
    //    return Result.success();
    //}
    @PostMapping("/add")
    @AutoLog("新增用户")
    public Result add(@RequestBody Admin admin){
        adminService.add(admin);
        return Result.success();
    }
    @PostMapping("/edit")
    @AutoLog("编辑用户")
    public Result edit(@RequestBody Admin admin){
        adminService.update(admin);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @AutoLog("删除用户")
    public Result delete(@PathVariable Integer id){
        adminService.deleteById(id);
        return Result.success();
    }
    @PostMapping("/login")
    @AutoLog("登录")
    public Result login(@RequestBody Admin admin, @RequestParam String key, HttpServletRequest request){
        //判断验证码是否正确
        if(!admin.getVerCode().toLowerCase().equals(CaptureConfig.CAPTURE_MAP.get(key))){
            //如果不相等，说明验证不通过
            CaptchaUtil.clear(request);
            return Result.error("验证码不正确");
        }
        Admin loginUser = adminService.login(admin);
        CaptureConfig.CAPTURE_MAP.remove(key);
        return Result.success(loginUser);
    }

    @PostMapping("/register")
    public Result register(@RequestBody Admin admin){
        adminService.add(admin);
        return Result.success();
    }
}

